package com.lxw.station.lzw;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lxw.station.api.GitXxApi;
import com.lxw.station.entity.GitProject;
import com.lxw.station.service.GitProjectService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import org.springframework.stereotype.Service;
import utils.GitUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


@Slf4j
@Service
public class DevelopmentalTask {

    @Resource
    GitProjectService gitProjectService;

    @SneakyThrows
    public static void main(String[] args) {

    }

    @SneakyThrows
    private List<String> keywords() {
        File dir = new File("src/main/resources/tmp");
        List<String> list = new ArrayList<>();
        for (File path : dir.listFiles()) {
            String json = new String(Files.readAllBytes(Paths.get(path.getAbsolutePath())));
            JSONObject jsonObject = JSON.parseObject(json);
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
            for (int i = 0; i < jsonArray.size(); i++) {
                String title = jsonArray.getJSONObject(i).getString("title");
                String substring = title.substring(title.indexOf("【") + 1, title.indexOf("】"));
                System.out.println(substring);
                list.add(substring);
            }
        }
        return list;
    }

    public void init() {
        clone2local();
    }

    /**
     * 打包
     */
    private void extracted() {
        // kw
        for (File file : new File("E:\\csdn\\待上传\\lzw的成长任务").listFiles()) {
            try {
                // id

                File[] files = file.listFiles();
                if (files.length == 2) {
                    continue;
                }
                for (File listFile : files) {
                    String projectId = listFile.getName();
                    List<GitProject> list = gitProjectService.list(new LambdaQueryWrapper<GitProject>().eq(GitProject::getProjectId, projectId));
                    GitProject gitProject = list.get(0);
                    String zipFileFullName = "E:\\csdn\\待上传\\lzw的成长任务\\" + gitProject.getKeyWord() + "\\" + gitProject.getZipName() + ".zip";
                    packageZip(zipFileFullName, listFile.listFiles()[0].getAbsolutePath(), gitProject.getProjectName(), gitProject.getProjectId());
                }
            } catch (Exception e) {

            }
        }
    }

    /**
     * 下载成长任务到本地
     */
    private void clone2local() {
        for (String keyword : keywords()) {
            List<GitProject> list = gitProjectService.list(new LambdaQueryWrapper<GitProject>().eq(GitProject::getKeyWord, keyword));
            Optional<GitProject> first = list.stream().filter(item -> item.getZipName().length() > 20 && item.getZipName().length() < 60).findFirst();
            if (first.isPresent()) {
                GitProject best = first.get();
                System.out.println(JSON.toJSONString(best));
                String dir = "E:\\csdn\\待上传\\lzw的成长任务\\" + keyword + "\\" + best.getProjectId() + "\\" + best.getProjectName();
                GitUtils.clone(best.getProjectUrl(), dir);
            }
        }
    }

    /**
     * 从gitee搜索成长任务并保存到数据库
     */
    private void queryTaskAndSave() {
        for (String keyword : keywords()) {
            try {
                List<GitProject> gitProjects = GitXxApi.giteeProjects(keyword);
                for (GitProject gitProject : gitProjects) {
                    gitProjectService.save(gitProject.setNotes("成长任务"));
                }
            } catch (Exception e) {
                log.error(keyword);
            }
        }
    }


    @SneakyThrows
    public void packageZip(String zipFileFullName, String folder, String rootFolder, String comment) {
        File file = new File(zipFileFullName);
        if (file.exists()) {
            log.info("文件已存在:{}", zipFileFullName);
            return;
        }
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        ZipParameters parameters = new ZipParameters();
        parameters.setRootFolderNameInZip(rootFolder);
        // 压缩包位置
        ZipFile zipFile = new ZipFile(zipFileFullName);
        // 添加文件夹到压缩文件，包括子文件夹和文件
        zipFile.addFolder(new File(folder), parameters);
        zipFile.setComment(comment);
        log.info("打包完成:{}", zipFileFullName);
    }
}
